package com.ruoyi.web.controller.ai;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.web.controller.pic.service.IAPicService;
import com.ruoyi.web.controller.study_path.service.IARouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;

@RestController
@EnableAsync
@RequestMapping("/ai")
public class aiController extends BaseController {

    @Value("${dashscope.api-key}")
    private String apiKey;

    @Value("${dashscope.model}")
    private String model;
    @Autowired
    private IAPicService aPicService;

  @Autowired
  private IARouteService aRouteService;

    @PostMapping("/talk")
    public ResponseEntity<?> talkWithAI(@RequestBody Map<String, String> requestBody) {
        String userMessage = requestBody.get("message");
        System.out.println("用户消息：" + userMessage);
        if (userMessage == null || userMessage.isEmpty()) {
            return ResponseEntity.badRequest().body("用户消息不能为空");
        }
        try {
            GenerationResult result = callWithMessage(userMessage+"(提炼关键点)",apiKey,model);
            String content = result.getOutput().getChoices().get(0).getMessage().getContent();
            System.out.println("AI消息："+content);
            String newtext = content.replace("#", "").replace("- **", "  · ").replace("-", "").replace("**", "");
            // 返回 JSON 格式的响应
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", newtext);
            return ResponseEntity.ok(response);
        } catch (NoApiKeyException e) {
            return ResponseEntity.status(500).body("服务配置错误");
        } catch (InputRequiredException e) {
            return ResponseEntity.badRequest().body("输入不合法");
        } catch (ApiException e) {
            return ResponseEntity.status(503).body("AI服务暂不可用");
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("系统繁忙");
        }
    }

    public static GenerationResult callWithMessage(String userMessage,String apiKey,String model) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(userMessage)  // 使用传入的用户消息
                .build();
        GenerationParam param = GenerationParam.builder()
                .apiKey(apiKey)
                .model(model)
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }
//http://localhost/dev-api/ai/get_pic
  @PostMapping("/get_pic")
  public ResponseEntity<?> get_pic(@RequestBody Map<String, String> requestBody) {
    String userMessage = requestBody.get("class_name");
    System.out.println("用户消息：" + userMessage);
    System.out.println("className：" + requestBody.get("className"));
    System.out.println("classId：" + requestBody.get("classId"));
    if (userMessage == null || userMessage.isEmpty()) {
      return ResponseEntity.badRequest().body("用户消息不能为空");
    }
    try {
      GenerationResult result = callWithMessage("我需要生成 " + userMessage + " 课程的知识图谱，请你按照下面格式生成图谱节点（节点一：子节点一，子节点二。节点二：子节点一，子节点二。）方便我做数据清洗，提取", apiKey, model);
      String content = result.getOutput().getChoices().get(0).getMessage().getContent();
      System.out.println("AI消息：" + content);
      String newtext = content.replace("#", "").replace("- **", "  · ").replace("-", "").replace("**", "");
      // 返回 JSON 格式的响应
      //设置知识图谱节点
      aPicService.setPicNode(newtext,requestBody.get("class_id"),getUserId(),userMessage);


      //设置学习路径节点
      GenerationResult result2 = callWithMessage("我需要生成 " + userMessage + " 课程的学习路径，每一个节点附上对应的学习网址(网址为菜鸟教程，网址不需要加如何描述，直接跟在路径后),输出格式如下（使用数组的方式输出，可以把最终的数组抽象成一个完全二叉树，除了根节点也就是第一个节点，其他节点的node都加上一个学习链接，这个树的高度为3，只有七个节点）只用输出数据，不需要解释", apiKey, model);
      String content2 = result2.getOutput().getChoices().get(0).getMessage().getContent();
      System.out.println("AI消息：" + content2);
      String newtext2 = content2.replace("#", "").replace("- **", "  · ").replace("-", "").replace("**", "").replace("/n","");
      // 返回 JSON 格式的响应
      System.out.println("newtext2 = " + newtext2);
      aRouteService.setRouNode(newtext2,requestBody.get("class_id"),getUserId(),userMessage);





      Map<String, Object> response = new HashMap<>();
      response.put("status", "success");
      response.put("message", newtext2);
      return ResponseEntity.ok(response);
    } catch (NoApiKeyException e) {
      return ResponseEntity.status(500).body("服务配置错误");
    } catch (InputRequiredException e) {
      return ResponseEntity.badRequest().body("输入不合法");
    } catch (ApiException e) {
      return ResponseEntity.status(503).body("AI服务暂不可用");
    } catch (Exception e) {
      return ResponseEntity.internalServerError().body("系统繁忙");
    }
  }


}
